﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Web;
using com.nm.ApiServer.Attributes;
using com.nm.Attributes;
using com.nm.Cache;
using com.nm.Helper;
using com.nm.Security;
using com.nm.db.Models;

// ReSharper disable once CheckNamespace
namespace com.nm.ApiServer {
	/// <summary>
	/// 认证
	/// </summary>
	public class TokenHandler : BaseHandler {
		/// <summary>
		/// 单位：秒
		/// </summary>
		private const int Timeout = 7200;
        /// <summary>
        /// 获取API 访问凭据（AccessToken）
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="secret"></param>
        /// <returns></returns>
        [Description("获取系统Token（System AccessToken）")]
        [ReturnType(typeof(SystemAccessToken))]
        [ApiVersion("1.0.0")]
        public ApiResult Get([ParamDescription("应用ID")]string appid, 
            [ParamDescription("访问密钥")]string secret) {
			Guid guid;
			if (Guid.TryParse(appid, out guid) == false) {
				throw new ArgumentException("无效的AppID", nameof(appid));
			}
			using (var dc = new db.Models.Systems.SysEntities()) {
				var app = dc.yhAPIApp.FirstOrDefault(item => item.ID == guid && item.AppSecret == secret);
				if (app == null) {
					return Error("无效请求", 404);
				}
				var token = APIHandlerFactory.createAccessToken(app.ID, app.AppSecret);
				RedisCache.AddString(token, app.ToJson(), Timeout/60);
				//myCache.Insert(token, app.ToJson(), Timeout, CacheItemPriority.Default);
				return Success(new SystemAccessToken {
					AccessToken = token,
					TimeOut = Timeout
				});
			}
		}
		/// <summary>
		/// 初始化主站的API配置信息
		/// </summary>
		public static string InitWebAccessToken(bool cache = false)
		{
			var cacheKey = "WEB-SITE-APP-INFO:" + MD5.Compute(HttpContext.Current.Server.MapPath("~/"));
			if (cache) {
				if (RedisCache.Exists(cacheKey)){
					var token = RedisCache.GetString(cacheKey);
					if (RedisCache.Exists(token))
						return token;
				}
			}
			using (var dc = new db.Models.Systems.SysEntities()) {
				var app = dc.yhAPIApp.FirstOrDefault(item => item.AppType==0);
				if (app == null) {
					throw new Exception("请配置主站的App信息");
				}
				var token = APIHandlerFactory.createAccessToken(app.ID, app.AppSecret);
				RedisCache.AddString(token, app.ToJson(), Timeout / 60);
				RedisCache.MaxString(cacheKey, token);
				return token;
			}
		}
        /// <summary>
        /// 系统SystemAccessToken
        /// </summary>
        public class SystemAccessToken{
            /// <summary>
            /// AccessToken
            /// </summary>
            [ParamDescription("System AccessToken")]
            public string AccessToken { get; set; }

            /// <summary>
            /// 超时时间，从请求的时间起。单位（秒）
            /// </summary>
            [ParamDescription("超时时间，从请求的时间起。单位（秒）", DefaultValue = 7200)]
            public int TimeOut { get; set; }
        }
	}
}
